package com.jci.vsd.activity;

import android.app.Notification;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;

import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Toast;

import com.jci.vsd.R;

import com.jci.vsd.activity.Reim.MyReimApprovalDetailActivity;
import com.jci.vsd.bean.MessageBean;
import com.jci.vsd.bean.notice.UnreadNoticeBean;
import com.jci.vsd.constant.AppConstant;
import com.jci.vsd.model.MsgModel;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.view.widget.SimpleToast;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/12/10 0010.
 *  轮巡消息service
 *
 */


public class NoticeMsgService extends Service {
    private Timer timer;
    private static final int TIME_PERIAO = 30 * 1000;
    private Notification notification;
    private NotificationManager manager;
    private NotificationCompat.Builder mBuilder;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Loger.e("service-onStartCommand");
        startTimer();
        return super.onStartCommand(intent, flags, startId);
    }


    @Override
    public void onDestroy() {
        endTimer();
        super.onDestroy();
    }


    private void startTimer() {
        endTimer();
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Loger.e("startTimer == ");
                // getUnreadMsg();
                getReimMsgs();
            }
        };
        timer.schedule(timerTask, 0, TIME_PERIAO);
    }

    private void endTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;

        }
    }

    /**
     * 请求未读消息
     */
    private void getUnreadMsg() {
        new MsgModel().getUnreadMsg(new MsgModel.OnUnReadMsgListener() {
            @Override
            public void onReceiveMsg(String title, List<UnreadNoticeBean> unreadNoticeBeanList) {
                handleMsg(title, unreadNoticeBeanList);
            }

            @Override
            public void onReimMsg(String title, List<MessageBean> msgs) {

            }
        });
    }

    /**
     * 请求未读消息
     */
    private void getReimMsgs() {
        new MsgModel().getUnreadMsg(new MsgModel.OnUnReadMsgListener() {
            @Override
            public void onReceiveMsg(String title, List<UnreadNoticeBean> unreadNoticeBeanList) {
                handleMsg(title, unreadNoticeBeanList);

            }

            @Override
            public void onReimMsg(String title, List<MessageBean> msgs) {
                Loger.e("msgService--" + title);

                if (msgs.size() > 0) {
                    MessageBean msgBean = msgs.get(0);
                    handleReimMsg(title, msgBean);
                }
//                for (int i = 0; i < msgs.size(); i++) {
//                    msgBean = msgs.get(i);
//                    if (!msgBean.isIsRead()) {
//
//                        handleReimMsg(title, msgBean);
//                    }
//                    break;
//
//                }

            }
        });
    }

    /**
     * 发送广播和通知
     */
    private void handleMsg(String title, List<UnreadNoticeBean> unreadNoticeBeanList) {
        Loger.e(title + "未读消息数量：" + unreadNoticeBeanList.size());
        Intent intent = new Intent(AppConstant.NOTICE_ACTION);
        intent.putExtra("title", title);
        intent.putExtra("count", unreadNoticeBeanList.size());
        sendBroadcast(intent);

        if (unreadNoticeBeanList.size() > 0) {
            showNotification(unreadNoticeBeanList);
        }
    }

    /**
     * 发送广播和通知
     */
    private void handleReimMsg(String title, MessageBean msgbean) {
        Loger.e(title + "handleReimMsg：msgService");
        if (msgbean.getType() != 0) {
            Intent intent = new Intent(AppConstant.NOTICE_ACTION);
            intent.putExtra("title", title);
            intent.putExtra("count", 1);
            sendBroadcast(intent);


            showReimNotification(msgbean);
        } else {
            //登录超时判断
            SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_SHORT);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }


    }

    /**
     * 创建通知渠道，适配8.0
     */
//    private void createNotificationChannel() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel channel = new NotificationChannel(1, "notification_name", NotificationManager.IMPORTANCE_DEFAULT);
//            channel.enableLights(false); //是否在桌面icon右上角展示小红点
//            channel.setLightColor(Color.GREEN); //小红点颜色
//            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
//            channel.enableVibration(false);
//            channel.setSound(Settings.System.DEFAULT_NOTIFICATION_URI, Notification.AUDIO_ATTRIBUTES_DEFAULT);
//            manager.createNotificationChannel(channel);
//        }
//   }


    /**
     * 获取SDK的API Level
     *
     * @return
     */
    public static int getSDK() {
        return android.os.Build.VERSION.SDK_INT;
    }


    /**
     * 发送通知
     */
    private void showReimNotification(MessageBean messageBean) {
        NotificationCompat.Builder builderChannel;
        Loger.e("showReimNotification--;msgService sdk=" + getSDK());
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Loger.e("---VERSION_CODES.O");
        }

        if (Build.VERSION.SDK_INT >= 26) {
            Loger.e("---SDK_INT>=26");
            String id = "channel_1";
            String description = "123";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;

            NotificationChannel mChannel = new NotificationChannel(id, "123", importance);
            mChannel.setDescription(description);

            mChannel.enableLights(true);//是否在桌面icon右上角展示小红点
            mChannel.setLightColor(Color.RED);
            mChannel.enableVibration(true);
            mChannel.setShowBadge(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            manager.createNotificationChannel(mChannel);
            String channelId = mChannel.getId();
            Loger.e("---channelId=" + channelId);
           builderChannel = new NotificationCompat.Builder(getApplicationContext(),channelId);


            // builder.setChannelId(channelId);

        } else {
          builderChannel=new NotificationCompat.Builder(getApplicationContext(),null);

        }

        //跳转意图
      //  Intent intent = new Intent(this, MainActivity.class);
        Intent intent = new Intent(this, MainNewActivity.class);
        intent.putExtra(AppConstant.KEY_TYPE, "msg");

        //通知栏显示内容
        builderChannel.setTicker(messageBean.getTitle());
        //通知栏消息下拉时显示的标题
        builderChannel.setContentTitle(messageBean.getTitle());
        //通知消息下拉是显示的文本内容
        builderChannel.setContentText(messageBean.getContext());
      //  builderChannel.setNumber(1);
        //接收到通知时，按手机的默认设置进行处理，声音，震动，灯
        builderChannel.setDefaults(Notification.DEFAULT_ALL);
        //通知栏显示图标
        builderChannel.setSmallIcon(R.drawable.notice_42_42);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builderChannel.setContentIntent(pendingIntent);
        notification = builderChannel.build();
        //点击跳转后消失
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        manager.notify(1, notification);

    }




    /**
     * 发送通知
     */
    private void showNotification(List<UnreadNoticeBean> unreadNoticeBeanList) {

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            Loger.e("---VERSION_CODES.O");
//        }
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(getApplicationContext());
        //跳转意图
        Intent intent = new Intent(this, MainNewActivity.class);
        intent.putExtra(AppConstant.KEY_TYPE, "msg");
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
        //通知栏显示内容
        builder.setTicker(unreadNoticeBeanList.get(0).getMsgTitle());
        //通知栏消息下拉时显示的标题
        builder.setContentTitle(unreadNoticeBeanList.get(0).getMsgTitle());
        //通知消息下拉是显示的文本内容
        builder.setContentText(unreadNoticeBeanList.get(0).getMsgContent());
        builder.setNumber(1);
        //接收到通知时，按手机的默认设置进行处理，声音，震动，灯
        builder.setDefaults(Notification.DEFAULT_ALL);
        //通知栏显示图标
        builder.setSmallIcon(R.drawable.notice_42_42);
        builder.setContentIntent(pendingIntent);
        notification = builder.build();
        //点击跳转后消失
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        manager.notify(1, notification);

    }



}
